import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/material.dart';
import 'package:ls_work/mvp/svp_progress.dart';
import 'package:ls_work/net/HttpUtil.dart';
import 'package:ls_work/net/net.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/res/styles.dart';
import 'package:ls_work/a_yyt/widget/address_book_cell.dart';
import 'package:ls_work/a_yyt/models/address_book_entity.dart';
import 'package:ls_work/util/toast.dart';
import 'dart:convert';
import 'package:dio/dio.dart';

import '../../util/flat_button.dart';



class HomeAddressBookPage extends StatefulWidget {
  @override
  _HomeAddressBookPageState createState() => _HomeAddressBookPageState();
}

class _HomeAddressBookPageState extends State<HomeAddressBookPage> {
  List<AddressBookSection> dataList = [];
  String nameStr = '';
  int current = 0;
  @override
  void initState() {
    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _fectData();
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('通讯录'),
        elevation: 0.5,
      ),
      body: Container(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Container(
              width: double.infinity,
              height: 50,
              child: FlatsButton(
                child: Row(
                  children: [
                    Icon(
                      Icons.arrow_drop_down,
                      color: Colours.text_gray,
                      size: 30,
                    ),
                    Text('$nameStr', style: TextStyles.textGray18),
                  ],
                ),
                onPressed: _showBottomSheet,
              ),
            ),
            Container(
              width: double.infinity,
              height: 1,
              color: Colours.bg_gray,
            ),
            Expanded(
              child: dataList.length <= 0
                  ? Container(
                      child: Center(
                        child: Text(
                          '暂无数据',
                          style: TextStyles.textGray14,
                        ),
                      ),
                    )
                  : ListView.separated(
                      itemCount: dataList[current].staffPhoneBooks?.length??0,
                      itemBuilder: (BuildContext context, int index) {
                        return AddressBookCell(
                          info: dataList[current].staffPhoneBooks![index],
                        );
                      },
                      separatorBuilder: (BuildContext context, int index) {
                        return Divider();
                      },
                    ),
            )
          ],
        ),
      ),
    );
  }

  _fectData() {
    SVProgressHUD page = SVProgressHUD(context);
    page.showProgress();
    HttpUtil.instance.getDio().post(HttpApi.findPhoeBookList).then((r) {
      ///
      page.closeProgress();
      if (r.statusCode == 200) {
        Map<String, dynamic> map = json.decode(r.toString());

        if (map["code"].toString() == "0") {
          if (map['data'] != null) {
            AddressBookEntity model = AddressBookEntity.fromJson(map['data']);
            setState(() {
             if((model.rows??[]).isNotEmpty){
               dataList = model.rows??[];
               nameStr = model.rows!.first.officeName ?? '';
             }
            });
          } else {
            Toast.show(map["msg"]);
          }
        } else {
          Toast.show(map["msg"]);
        }
      } else {
        Toast.show(r.statusCode.toString());
      }
    }).catchError((e) {
      page.closeProgress();
      print(e.toString());
      Toast.show(getErrorMessage(e));
    });
  }

  ///底部弹窗
  _showBottomSheet() {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: dataList.map((f) {
              return _item(f);
            }).toList(),
          ),
        );
      },
    );
  }

  Widget _item(AddressBookSection info) {
    return InkWell(
      onTap: () {
        setState(() {
          nameStr = info.officeName ?? '';
          current = dataList.indexOf(info);
          Navigator.pop(context);
        });
      },
      child: Container(
        padding: EdgeInsets.all(20),
        child: Center(
          child: Text(info.officeName ?? ''),
        ),
      ),
    );
  }
}
